package com.l.web;

import com.l.service.BaseRepository;
import com.l.util.ExcelUtil;
import org.apache.log4j.Logger;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.*;
import java.util.stream.IntStream;

/**
 * Created by gyy on 2016/6/18.
 */
@Controller
public class IndexController {
    private static Logger logger = Logger.getLogger(IndexController.class);
    @Autowired
    private BaseRepository baseRepository;

    @RequestMapping("/")
    public String index(@RequestParam(value = "name", defaultValue = "Sai", required = false) String name, Model model) {
        model.addAttribute("name", name);

        logger.info("test log");

        return "index";
    }

    @RequestMapping("/init")
    @ResponseBody
    public Map<String, Object> init() {
        Map<String, Object> result = new HashMap<>();
        List<String> category = new ArrayList<>();
        List<Float> data = new ArrayList<>();

        String path = Thread.currentThread().getContextClassLoader().getResource("data/600859-2016-06-17.xlsx").getFile();
        try {
            List<List<Object>> rows = ExcelUtil.read(path);

            rows.remove(0);
            Collections.reverse(rows);

            rows.forEach(r -> {
                IntStream.range(0, r.size())
                        .forEach(colIndex -> {
                            switch (colIndex) {
                                case 1:
                                    category.add(r.get(colIndex).toString());
                                    break;
                                case 2:
                                    data.add(Float.parseFloat(r.get(colIndex).toString()));
                                    break;
                                default:
                                    break;
                            }
                        });
            });

            result.put("category", category);
            result.put("data", data);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } catch (InvalidFormatException e) {
            logger.error(e.getMessage(), e);
        }

        return result;
    }
}
